package com.github.caijh.mall.config;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Data
@Configuration
public class TaskExecutorConfig {

    //普通模式
    private int taskCorePoolSize = 20; //核心线程池数量
    private int taskMaxPoolSize = 100; //最大线程
    private int taskQueueCapacity = 200; //缓存队列条数
    private int taskKeepAliveSecond = 10; //允许的空闲时间
    private String taskNamePrefix = "task-executor-"; //线程名称前缀


    //普通模式
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        return initTaskExecutor(
                getTaskCorePoolSize(),
                getTaskMaxPoolSize(),
                getTaskQueueCapacity(),
                getTaskKeepAliveSecond(),
                getTaskNamePrefix()
        );
    }

    /**
     * 初始化TaskExecutor
     *
     * @param corePoolSize    int 默认线程数
     * @param maxPoolSize     int 最大线程数
     * @param queueCapacity   int 缓冲队列长度
     * @param keepAliveSecond int 允许空闲时间
     * @param namePrefix      String  名称的前缀
     * @return ThreadPoolTaskExecutor
     */
    private ThreadPoolTaskExecutor initTaskExecutor(int corePoolSize, int maxPoolSize,
                                                    int queueCapacity, int keepAliveSecond, String namePrefix) {
        return initTaskExecutor(corePoolSize, maxPoolSize, queueCapacity, keepAliveSecond, namePrefix,
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

    /**
     * 初始化TaskExecutor
     *
     * @param corePoolSize             int 默认线程数
     * @param maxPoolSize              int 最大线程数
     * @param queueCapacity            int 缓冲队列长度
     * @param keepAliveSecond          int 允许空闲时间
     * @param namePrefix               String  名称的前缀
     * @param rejectedExecutionHandler 线程池满的时候如何处理
     * @return ThreadPoolTaskExecutor
     */
    private ThreadPoolTaskExecutor initTaskExecutor(int corePoolSize, int maxPoolSize,
                                                    int queueCapacity, int keepAliveSecond, String namePrefix,
                                                    RejectedExecutionHandler rejectedExecutionHandler) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);//核心线程数(默认线程数)
        executor.setMaxPoolSize(maxPoolSize);//最大线程数
        executor.setQueueCapacity(queueCapacity);//缓冲队列数
        executor.setKeepAliveSeconds(keepAliveSecond);//允许线程空闲时间(单位默认为秒)
        executor.setThreadNamePrefix(namePrefix);//线程名前缀

        //线程池对拒绝任务的处理策略，
        executor.setRejectedExecutionHandler(rejectedExecutionHandler);

        //初始化
        executor.initialize();
        return executor;
    }

}
